package com.yuanqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanqi.entity.Inventory;
import com.yuanqi.entity.InventoryTxn;
import com.yuanqi.entity.WareDelivery;
import com.yuanqi.entity.WareDeliveryItem;
import com.yuanqi.mapper.InventoryMapper;
import com.yuanqi.mapper.InventoryTxnMapper;
import com.yuanqi.mapper.WareDeliveryItemMapper;
import com.yuanqi.mapper.WareDeliveryMapper;
import com.yuanqi.mapper.WareWarehouseMapper;
import com.yuanqi.service.InventoryService;
import com.yuanqi.service.WareDeliveryItemService;
import com.yuanqi.service.WareDeliveryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.*;

/**
* @author HP
* @description 针对表【ware_delivery(出库单)】的数据库操作Service实现
* @createDate 2025-08-26 14:58:48
*/
@Slf4j
@Service
public class WareDeliveryServiceImpl extends ServiceImpl<WareDeliveryMapper, WareDelivery>
    implements WareDeliveryService{

    @Autowired
    private WareDeliveryItemMapper wareDeliveryItemMapper;
    
    @Autowired
    private WareDeliveryItemService wareDeliveryItemService;
    
    @Autowired
    private InventoryService inventoryService;
    
    @Autowired
    private InventoryMapper inventoryMapper;
    
    @Autowired
    private InventoryTxnMapper inventoryTxnMapper;
    
    @Autowired
    private com.yuanqi.mapper.SkuMapper skuMapper;
    
    @Autowired
    private com.yuanqi.mapper.ProductMapper productMapper;
    
    @Autowired
    private WareWarehouseMapper wareWarehouseMapper;

    @Override
    public IPage<WareDelivery> listDeliveries(Integer page, Integer size, String deliveryCode, Long warehouseId, Integer status) {
        Page<WareDelivery> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<WareDelivery> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(deliveryCode)) {
            queryWrapper.like(WareDelivery::getDeliveryCode, deliveryCode);
        }
        
        if (warehouseId != null) {
            queryWrapper.eq(WareDelivery::getWarehouseId, warehouseId);
        }
        
        if (status != null) {
            queryWrapper.eq(WareDelivery::getStatus, status);
        }
        
        queryWrapper.orderByDesc(WareDelivery::getCreatedAt);
        
        return this.page(pageParam, queryWrapper);
    }

    @Override
    public Map<String, Object> getDeliveryDetail(Long id) {
        // 获取出库单主表信息
        WareDelivery delivery = this.getById(id);
        if (delivery == null) {
            return null;
        }
        
        // 获取出库单明细
        LambdaQueryWrapper<WareDeliveryItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WareDeliveryItem::getDeliveryId, id);
        List<WareDeliveryItem> items = wareDeliveryItemMapper.selectList(queryWrapper);
        
        Map<String, Object> result = new HashMap<>();
        result.put("delivery", delivery);
        result.put("items", items);
        
        return result;
    }

    @Override
    @Transactional
    public boolean createDelivery(WareDelivery delivery, List<Map<String, Object>> itemsData) {
        // 生成出库单号
        if (!StringUtils.hasText(delivery.getDeliveryCode())) {
            delivery.setDeliveryCode("DEL" + System.currentTimeMillis());
        }
        
        // 设置初始状态为新建
        delivery.setStatus(0);
        delivery.setCreatedAt(new Date());
        
        // 保存出库单主表
        boolean saved = this.save(delivery);
        if (!saved) {
            return false;
        }
        
        // 保存出库单明细
        List<WareDeliveryItem> items = new ArrayList<>();
        for (Map<String, Object> itemData : itemsData) {
            WareDeliveryItem item = new WareDeliveryItem();
            item.setDeliveryId(delivery.getId());
            
            // 设置明细数据
            if (itemData.containsKey("soItemId") && itemData.get("soItemId") != null && !itemData.get("soItemId").toString().isEmpty()) {
                item.setSoItemId(Long.valueOf(itemData.get("soItemId").toString()));
            }
            
            if (itemData.containsKey("locationId") && itemData.get("locationId") != null && !itemData.get("locationId").toString().isEmpty()) {
                item.setLocationId(Long.valueOf(itemData.get("locationId").toString()));
            } else {
                // 设置默认库位ID为1（需要确保数据库中有id=1的库位记录）
                item.setLocationId(1L);
            }
            
            if (itemData.containsKey("skuId")) {
                item.setSkuId(Long.valueOf(itemData.get("skuId").toString()));
            }
            
            if (itemData.containsKey("batchNo")) {
                item.setBatchNo(itemData.get("batchNo").toString());
            }
            
            if (itemData.containsKey("qty") && itemData.get("qty") != null) {
                item.setQty(new BigDecimal(itemData.get("qty").toString()));
            } else {
                // 如果没有提供数量，设置默认值为1
                item.setQty(new BigDecimal("1"));
            }
            
            items.add(item);
        }
        
        return wareDeliveryItemService.saveBatch(items);
    }

    @Override
    @Transactional
    public boolean submitDelivery(Long id) {
        WareDelivery delivery = this.getById(id);
        if (delivery == null || (delivery.getStatus() != 0 && delivery.getStatus() != 4)) {
            return false;
        }
        
        // 更新状态为待审核
        delivery.setStatus(1);
        return this.updateById(delivery);
    }
    
    @Override
    @Transactional
    public boolean approveDelivery(Long id) {
        WareDelivery delivery = this.getById(id);
        if (delivery == null || delivery.getStatus() != 1) {
            return false;
        }
        
        // 更新状态为已审核
        delivery.setStatus(2);
        return this.updateById(delivery);
    }

    @Override
    @Transactional
    public boolean rejectDelivery(Long id) {
        WareDelivery delivery = this.getById(id);
        if (delivery == null || delivery.getStatus() != 1) {
            return false;
        }
        
        // 更新状态为已驳回
        delivery.setStatus(4);
        return this.updateById(delivery);
    }

    @Override
    @Transactional
    public boolean updateDelivery(WareDelivery delivery, List<Map<String, Object>> itemsData) {
        // 检查出库单是否存在且状态允许修改
        WareDelivery existingDelivery = this.getById(delivery.getId());
        if (existingDelivery == null || existingDelivery.getStatus() != 4) {
            return false; // 只有驳回状态的出库单才能修改
        }

        // 更新出库单基本信息
        boolean updateResult = this.updateById(delivery);
        if (!updateResult) {
            return false;
        }

        // 删除原有的出库单明细
        LambdaQueryWrapper<WareDeliveryItem> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(WareDeliveryItem::getDeliveryId, delivery.getId());
        wareDeliveryItemMapper.delete(deleteWrapper);

        // 添加新的出库单明细
        for (Map<String, Object> itemData : itemsData) {
            WareDeliveryItem item = new WareDeliveryItem();
            item.setDeliveryId(delivery.getId());
            item.setSkuId(Long.valueOf(itemData.get("skuId").toString()));
            item.setQty(new BigDecimal(itemData.get("qty").toString()));
            
            // 设置默认库位（可以根据业务需求调整）
            item.setLocationId(1L); // 默认库位ID，实际应该根据业务逻辑设置
            
            wareDeliveryItemMapper.insert(item);
        }

        return true;
    }

    @Override
    @Transactional
    public boolean executeDelivery(Long id) {
        // 获取出库单
        WareDelivery delivery = this.getById(id);
        if (delivery == null || delivery.getStatus() != 2) {
            return false;
        }

        // 获取出库单明细
        LambdaQueryWrapper<WareDeliveryItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WareDeliveryItem::getDeliveryId, id);
        List<WareDeliveryItem> items = wareDeliveryItemMapper.selectList(queryWrapper);

        // 更新库存和创建库存事务
        for (WareDeliveryItem item : items) {
            // 查询库存
            LambdaQueryWrapper<Inventory> inventoryQuery = new LambdaQueryWrapper<>();
            inventoryQuery.eq(Inventory::getSkuId, item.getSkuId())
                    .eq(Inventory::getWarehouseId, delivery.getWarehouseId())
                    .eq(Inventory::getLocationId, item.getLocationId());

            if (StringUtils.hasText(item.getBatchNo())) {
                inventoryQuery.eq(Inventory::getBatchNo, item.getBatchNo());
            }

            Inventory inventory = inventoryMapper.selectOne(inventoryQuery);

            // 获取仓库名称
            String warehouseName = "未知仓库";
            try {
                com.yuanqi.entity.WareWarehouse warehouse = wareWarehouseMapper.selectById(delivery.getWarehouseId());
                if (warehouse != null) {
                    warehouseName = warehouse.getWhName();
                }
            } catch (Exception e) {
                log.warn("获取仓库名称失败: {}", e.getMessage());
            }

            // 判断库存是否足够（检查 available_qty）
            if (inventory == null) {
                throw new RuntimeException(String.format("出库单号:%s, 销售单号:%s, 仓库:%s%n库存不足，无法出库", 
                    delivery.getDeliveryCode(), delivery.getSoId(), warehouseName));
            }
            
            if (inventory.getAvailableQty().compareTo(item.getQty()) < 0) {
                throw new RuntimeException(String.format("出库单号:%s, 销售单号:%s, 仓库:%s%n库存不足，无法出库", 
                    delivery.getDeliveryCode(), delivery.getSoId(), warehouseName));
            }

            // 更新库存：扣减 on_hand_qty 和 available_qty
            inventory.setOnHandQty(inventory.getOnHandQty().subtract(item.getQty()));
            inventory.setAvailableQty(inventory.getAvailableQty().subtract(item.getQty()));
            inventory.setUpdatedAt(new Date());

            inventoryMapper.updateById(inventory);

            // 写入库存事务记录
            InventoryTxn txn = new InventoryTxn();
            txn.setTxnCode("DEL-" + System.currentTimeMillis()); // 或 UUID.randomUUID()
            txn.setWarehouseId(delivery.getWarehouseId());
            txn.setLocationId(item.getLocationId());
            txn.setSkuId(item.getSkuId());
            txn.setBatchNo(item.getBatchNo());
            txn.setQty(item.getQty().negate());   // 出库为负数
            // 出库单没有成本信息，unitCost 可不填，保持 null
            txn.setTxnType("OUT");
            txn.setReferenceTable("ware_delivery");
            txn.setReferenceId(delivery.getId());
            txn.setRemark("出库单出库");

            inventoryTxnMapper.insert(txn);

        }

        // 更新出库单状态
        delivery.setStatus(3); // 已出库
        delivery.setShippedAt(new Date());
        this.updateById(delivery);

        return true;
    }


    @Override
    public List<Map<String, Object>> getDeliveryRecords(String deliveryCode, String productName, Long warehouseId, Long skuId, String startDate, String endDate) {
        // 查询出库单明细
        LambdaQueryWrapper<WareDeliveryItem> itemQueryWrapper = new LambdaQueryWrapper<>();
        itemQueryWrapper.eq(skuId != null, WareDeliveryItem::getSkuId, skuId);
        
        List<WareDeliveryItem> items = wareDeliveryItemMapper.selectList(itemQueryWrapper);
        
        List<Map<String, Object>> records = new ArrayList<>();
        for (WareDeliveryItem item : items) {
            WareDelivery delivery = this.getById(item.getDeliveryId());
            if (delivery == null) {
                continue;
            }
            
            // 应用过滤条件
            boolean shouldInclude = true;
            
            // 出库单号过滤
            if (StringUtils.hasText(deliveryCode) && !delivery.getDeliveryCode().contains(deliveryCode)) {
                shouldInclude = false;
            }
            
            // 仓库过滤
            if (warehouseId != null && !warehouseId.equals(delivery.getWarehouseId())) {
                shouldInclude = false;
            }
            
            // 日期过滤
            if (StringUtils.hasText(startDate) && delivery.getCreatedAt() != null) {
                try {
                    Date start = java.sql.Date.valueOf(startDate);
                    if (delivery.getCreatedAt().before(start)) {
                        shouldInclude = false;
                    }
                } catch (Exception ignored) {}
            }
            
            if (StringUtils.hasText(endDate) && delivery.getCreatedAt() != null) {
                try {
                    Date end = java.sql.Date.valueOf(endDate);
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(end);
                    cal.add(Calendar.DAY_OF_MONTH, 1); // 包含结束日期当天
                    if (delivery.getCreatedAt().after(cal.getTime())) {
                        shouldInclude = false;
                    }
                } catch (Exception ignored) {}
            }
            
            // 商品名称过滤
            if (StringUtils.hasText(productName)) {
                try {
                    com.yuanqi.entity.Sku sku = skuMapper.selectById(item.getSkuId());
                    if (sku != null) {
                        com.yuanqi.entity.Product product = productMapper.selectById(sku.getProductId());
                        if (product == null || !product.getProductName().contains(productName)) {
                            shouldInclude = false;
                        }
                    } else {
                        shouldInclude = false;
                    }
                } catch (Exception e) {
                    shouldInclude = false;
                }
            }
            
            if (!shouldInclude) {
                continue;
            }
            
            Map<String, Object> record = new HashMap<>();
            record.put("id", item.getId());
            record.put("deliveryId", delivery.getId());
            record.put("deliveryCode", delivery.getDeliveryCode());
            record.put("soId", delivery.getSoId());
            record.put("skuId", item.getSkuId());
            record.put("qty", item.getQty());
            record.put("batchNo", item.getBatchNo());
            record.put("locationId", item.getLocationId());
            record.put("warehouseId", delivery.getWarehouseId());
            record.put("status", delivery.getStatus());
            record.put("shippedAt", delivery.getShippedAt());
            record.put("createdAt", delivery.getCreatedAt());
            
            // 添加商品信息
            try {
                com.yuanqi.entity.Sku sku = skuMapper.selectById(item.getSkuId());
                if (sku != null) {
                    record.put("skuCode", sku.getSkuCode());
                    com.yuanqi.entity.Product product = productMapper.selectById(sku.getProductId());
                    if (product != null) {
                        record.put("productName", product.getProductName());
                        record.put("productCode", product.getSpuCode());
                    }
                }
            } catch (Exception ignored) {
                record.put("skuCode", "SKU-" + item.getSkuId());
                record.put("productName", "未知商品");
            }
            
            records.add(record);
        }
        
        return records;
    }
}




